package com.ruoyi.web.controller.byd;


import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.domain.BydProductionPlan;
import com.ruoyi.system.domain.vo.BydProductionPlanDto;
import com.ruoyi.system.domain.vo.UpdateDataDto;
import com.ruoyi.system.mapper.BydProductionPlanMapper;
import com.ruoyi.system.mapper.BydspecialPojectMapper;
import com.ruoyi.system.service.BydspecialPojectService;
import com.ruoyi.system.utils.PdfUtils;
import com.ruoyi.util.PdfPartNumberProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/bydProductionPlan")
public class BydProductionPlanController extends BaseController {
    @Autowired
    private BydProductionPlanMapper bydProductionPlanMapper;
    @Autowired
    private BydspecialPojectService bydspecialPojectService;
    @Autowired
    private BydspecialPojectMapper bydspecialPojectMapper;

    @PostMapping("/selectBydProductionPlan")
    public List<BydProductionPlan> selectBydProductionPlan(BydProductionPlanDto bydProductionPlanDto){
        return bydProductionPlanMapper.selectBydProductionPlanList(bydProductionPlanDto);
    }

    @PostMapping("/insertData")
    public R insertData(@RequestBody BydProductionPlanDto bydProductionPlanDto){
        if (bydProductionPlanDto == null){
           return R.fail("请正确填写数据");
        }
        int sum = bydProductionPlanMapper.insertData(bydProductionPlanDto);
        if (sum < 1) {
          return R.fail("请正确填写数据");
        }
       return R.ok("新增数据完成");
    }

    @PostMapping("/updateDataById")
    public R updateData(@RequestBody UpdateDataDto updateDataDto){
        if (updateDataDto == null) {
            return R.fail("请正确填写数据");
        }
        int sum = bydProductionPlanMapper.updateData(updateDataDto);
        if (sum < 1){
            return R.fail("更改数据失败，请联系管理员处理");
        }
        return R.ok("更改数据成功");
    }

    @GetMapping("/deleteById")
    public R deleteById(@RequestParam Long id){
        if (id ==null ){
           return R.fail("请选择需要删除的数据");
        }
        boolean result = bydProductionPlanMapper.deleteByid(id);
        if (!result){
            return R.fail("删除失败，请联系管理员处理");
        }
        return R.ok("删除成功");
    }

    /**
     * 上传附件并将附件地址保存在数据库
     * @param file
     * @param outputDir
     * @return
     * @throws IOException
     */
    @PostMapping("/process-by-part")
    public R processByPartNumber(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "outputDir", required = false) String outputDir) throws IOException {

        try {
            // 验证输入
            if (file.isEmpty()) {
                return R.fail("请上传pdf文件");
            }
            String fileNamePrefix = file.getOriginalFilename();;
            String nameWithoutExtension = fileNamePrefix.substring(0, fileNamePrefix.lastIndexOf("."));
            List<String> partNumbers = bydspecialPojectService.selectModelByOrder(nameWithoutExtension);
            if (partNumbers == null || partNumbers.isEmpty()) {
                return R.fail("至少提供一个零件号");
            }

            // 确定输出目录
            String outputDirectory;
            if (outputDir != null && !outputDir.isEmpty()) {
                outputDirectory = outputDir;
            } else {
                Path tempDir = Files.createTempDirectory("pdf-parts-" + System.currentTimeMillis());
                outputDirectory = tempDir.toString();
            }

            // 处理PDF
            PdfPartNumberProcessor processor = new PdfPartNumberProcessor(partNumbers, outputDirectory);
            Map<String, String> resultPaths = processor.processPdf(file.getInputStream());
            List<Map<String,String>> resulstPath = new ArrayList<>();
            resultPaths.forEach((productModel,productPath) ->{
                Map<String,String> map = new HashMap<>();
                map.put("productModel",productModel.toUpperCase());
                map.put("productPath",productPath);
                resulstPath.add(map);
            });
            bydspecialPojectMapper.batchUpdateProductPath(resulstPath);
             // 返回结果
            return R.ok("上传成功");
        } catch (IOException e) {
            return R.fail("处理PDF时发生错误: " + e.getMessage());
        } catch (Exception e) {
            return R.fail("发生未知错误: " + e.getMessage());
        }
    }

    /**
     * 预览附件
     * @param productModel
     * @return
     * @throws IOException
     */
    @GetMapping("/api/pdf/stream/{productModel}")
    public ResponseEntity<byte[]> getPdfStream(@PathVariable String productModel) throws IOException {

        String path = bydspecialPojectMapper.selectByProductModel(productModel);
        // 1. 读取PDF文件为字节数组
        byte[] pdfBytes = Files.readAllBytes(Paths.get(path));

        // 2. 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/pdf");
        headers.add("Content-Disposition", "inline; filename=\"" + productModel + ".pdf\"");
        return new ResponseEntity<>(pdfBytes, headers, HttpStatus.OK);
    }

    //下载pdf

}
